import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import axios from 'axios';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import './assets/style/font-awesome.css';
import './assets/style/style.less';
import './assets/style/iconfont/menu.less';
import * as echart from 'echarts';
import * as qiniu from 'qiniu-js';
import ZmTreeOrg from 'zm-tree-org';
import "zm-tree-org/lib/zm-tree-org.css";

import config from './config/index'

const appConfig = config.getConfig()

Vue.prototype.$appConfig = appConfig;
window.$appConfig = Vue.prototype.$appConfig;

Vue.use(ZmTreeOrg);
axios.defaults.baseURL = appConfig.baseURL;// 设置成你需要的默认地址
Vue.use(ElementUI);
axios.defaults.withCredentials = true;
Vue.config.productionTip = false;

var $http = axios.create({
    // baseURL:process.env.VUE_APP_BASE_URL,
    baseURL: '/',
    headers: {
        token: localStorage.getItem('token'),
        'Content-Type': "application/json",
        // 'Content-Type': "multipart/form-data",
        // 'Content-Type': "application/x-www-form-urlencoded",
    },
    withCredentials: true,
});
Vue.prototype.$http = $http;
Vue.prototype.$echarts = echart;
Vue.prototype.$qiniu = qiniu;
// 设置登录状态
if (localStorage.getItem('userInfo') != null) {
    store.commit('setUserInfo', JSON.parse(localStorage.getItem('userInfo')));
}

// 请求发前拦截，header中添加token
$http.interceptors.request.use(result => {
    if (Object.keys(store.state.userInfo).length > 0) {
        result.headers.token = store.state.userInfo.token;
    }
    return result;
});
// 响应拦截
$http.interceptors.response.use(response => {
    if (response.data.code == 8001) {
        store.commit('setUserInfo', {});
        localStorage.removeItem('userInfo');
        router.push({
            path: '/login',
            query: { refersh: window.location }
        });
    }
    return Promise.resolve(response.data);
}, error => {
    return Promise.reject(error);
});

// 路由守卫
router.beforeEach((to, from, next) => {
    const userInfo = localStorage.getItem('userInfo');
    if (!userInfo && to.path!== '/login') {
        next({
            path: '/login',
            query: {
                redirect: to.fullPath
            }
        });
    } else {
        next();
    }
});
// 跳转完成
router.afterEach((to, from) => {});

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');
